function G=adapcoding(E)

%Takes a matrix of elements in the 0..255 interval and generates a vector
%of coded values, generated through Golomb or by runs.
%Golomb parameter is set adaptively

%Pseudo-code
run_mode=0;
k_run=0;
[M,N]=size(E);
G=zeros(2*M*N,1);
G(1)=M;
G(2)=N;
G(3)=0;
G(4)=0;
last=4;
A=8;
nsamp=1;
cont=1;
nmax=4;
for i=1:M
   for j=1:N
       if (E(i,j)==512) %Enter run mode
           k_run=k_run+1;
           if run_mode==0
               run_mode=1;        
           end
           if k_run==254 %Greatest run possible
               run_mode=0;
               G(last+1)=255; %Code for entering run mode, assuming golomb cannot return 255 as binary EVER
               G(last+2)=k_run;
               k_run=0;
               last=last+2;
           end
       else
            if run_mode==1
               run_mode=0;
               G(last+1)=255; %Code for entering run mode, assuming golomb cannot return 255 as binary EVER
               G(last+2)=k_run;
               k_run=0;
               last=last+2;
            end
               k=ceil(A/nsamp);
               MGol=2^k;
               g=golomb(E(i,j),MGol);
               G(last+1:last+2)=g; %Golomb code should go here
               last=last+2;
               cont=cont+1;
                if nsamp==nmax;
                    nsamp=ceil(nmax/2);
                    A=floor(A/2);
                end
                nsamp=nsamp+1;
                A=A+invfunctionM(E(i,j));
       end
   end
end
if run_mode==1 %Never exited run mode
               G(last+1)=255; %Code for entering run mode, assuming golomb cannot return 255 as binary EVER
               G(last+2)=k_run;
               last=last+2;
end
G(last+1:last+2)=[255 255]; %Code for EOF